
import { PlusOutlined } from '@ant-design/icons';
import { Button, Space, Popconfirm, message, Switch, Tag, Drawer } from 'antd';
import { ProDescriptions } from '@ant-design/pro-components';
import React, { useState, useRef } from 'react';
import { useAccess, Access } from 'umi';
import SaveForm from './components/SaveForm';
import { query, update, add, get, statusChange } from './service';
import { useRequestHandle } from '@/utils/utils';
import operation from './operation';
import ProMaxTable from '@/components/ProMaxTable';

const PositionManage = () => {
  const [saveFormVisible, setSaveFormVisible] = useState(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const { canOperation, canShowOption } = useAccess();
  // 是否显示操作列
  const isShowOptionColumn = canShowOption([operation.update, operation.delete]);
  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 新增
  const addRequest = useRequestHandle(add, () => {
    message.success('创建成功.');
    setSaveFormVisible(false);
    reload();
  });
  // 更新
  const updateRequest = useRequestHandle(update, () => {
    message.success('更新成功.');
    setSaveFormVisible(false);
    setUpdateFormValues({});
    reload();
  });

  // 状态变更
  const statusChangeRequest = useRequestHandle(statusChange, () => {
    message.success('操作成功.');
    reload();
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 75,
    },
    {
      title: '职位名称',
      dataIndex: 'name',
      ellipsis: true,
      hideInSearch: true,
      render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      sorter: true,
      width: 100,
      render: (_, record) => {
        const isChecked = record.status === 1;
        const canChangeStatus = canOperation(operation.statusChange);
        if (!canChangeStatus) {
          return isChecked ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>;
        }
        const title = isChecked ? '确定要禁用该数据吗？' : '确定要启用该数据吗？';
        return (
          <>
            <Popconfirm
              placement="top"
              title={title}
              onConfirm={(e) => {
                e.stopPropagation();
                statusChangeRequest.run({ id: record.id });
              }}
              okText="确定"
              cancelText="取消"
            >
              <Switch
                loading={statusChangeRequest.loading}
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={isChecked}
              />
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      sorter: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 135,
      hideInTable: !isShowOptionColumn,
      render: (_, record) => (
        <Space>
          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const result = await get({ id: record.id });
                if (!result.success) {
                  message.error(result.message);
                  return;
                }
                setSaveFormVisible(true);
                setUpdateFormValues(result.data);
              }}
            >
              编辑
            </Button>
          </Access>

        </Space>
      ),
    },
  ];
  return (
    <>



      <ProMaxTable
        headerTitle={
          <Access key="create" accessible={canOperation(operation.create)}>
            <Button type="primary" onClick={() => setSaveFormVisible(true)}>
              <PlusOutlined /> 创建
            </Button>
          </Access>
        }
        actionRef={actionRef}
        rowKey="id"

        query={query}
        columns={columns}
        rowSelection={false}
        expandable={{ defaultExpandAllRows: true }}
      />

      <SaveForm
        onSubmit={async (value) => {
          const params = Object.assign(value, { status: value.status ? 1 : 0 });
          if (params.id) {
            updateRequest.run(params);
          } else {
            addRequest.run(params);
          }
        }}
        onCancel={() => {
          setSaveFormVisible(false);
          setUpdateFormValues({});
        }}
        loading={updateRequest.loading || addRequest.loading}
        modalVisible={saveFormVisible}
        record={updateFormValues}
      />

      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.id,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </>
  );
};

export default PositionManage;
